/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtpserver.handler.fastfail;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Required;

import com.googlecode.asyncmail.common.MailAddress;
import com.googlecode.asyncmail.smtpserver.SMTPSession;
import com.googlecode.asyncmail.smtpserver.hook.HookResult;
import com.googlecode.asyncmail.smtpserver.hook.HookReturnCode;
import com.googlecode.asyncmail.smtpserver.hook.RcptHook;

/**
 * This handler can be used for providing a spam trap. IPAddresses which send
 * emails to the configured recipients will get blacklisted for the configured
 * time.
 */
public class SpamTrapHandler implements RcptHook {

    // Map which hold blockedIps and blockTime in memory
    private Map<String, Long> blockedIps = new HashMap<String, Long>();

    private Collection<String> spamTrapRecips = new ArrayList<String>();

    // Default blocktime 12 hours
    private long blockTime = 4320000;

    private Log logger;

    @Required
    public void setLogger(Log logger) {
        this.logger = logger;
    }

    @Required
    public void setSpamTrapRecipients(Collection<String> spamTrapRecips) {
        this.spamTrapRecips = spamTrapRecips;
    }

    public void setBlockTime(long blockTime) {
        this.blockTime = blockTime;
    }

    /**
     * @see com.googlecode.asyncmail.smtpserver.hook.RcptHook#doRcpt(com.googlecode.asyncmail.smtpserver.SMTPSession,
     *      org.apache.mailet.MailAddress, org.apache.mailet.MailAddress)
     */
    public HookResult doRcpt(SMTPSession session, MailAddress sender,
            MailAddress rcpt) {
        if (isBlocked(session.getRemoteIPAddress())) {
            return new HookResult(HookReturnCode.DENY);
        } else {

            if (spamTrapRecips.contains(rcpt.toString().toLowerCase())) {
                addIp(session.getRemoteIPAddress());

                return new HookResult(HookReturnCode.DENY);
            }
        }
        return new HookResult(HookReturnCode.DECLINED);
    }

    /**
     * Check if ipAddress is in the blockList.
     * 
     * @param ip
     *                ipAddress to check
     * @return true or false
     */
    private boolean isBlocked(String ip) {
        Object rawTime = blockedIps.get(ip);

        if (rawTime != null) {
            long blockTime = ((Long) rawTime).longValue();

            if (blockTime > System.currentTimeMillis()) {
                logger.debug("BlockList contain Ip " + ip);
                return true;
            } else {
                logger.debug("Remove ip " + ip + " from blockList");

                synchronized (blockedIps) {
                    blockedIps.remove(ip);
                }
            }
        }
        return false;
    }

    /**
     * Add ipaddress to blockList
     * 
     * @param ip
     *                IpAddress to add
     */
    private void addIp(String ip) {
        long bTime = System.currentTimeMillis() + blockTime;

        logger.debug("Add ip " + ip + " for " + bTime + " to blockList");

        synchronized (blockedIps) {
            blockedIps.put(ip, new Long(bTime));
        }

    }
}
